
#include "sle_low_latency.h"

#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include "cmsis_os2.h"
#include "app_init.h"
#include "soc_osal.h"

#include "common_def.h"
#include "pinctrl.h"
#include "uart.h"

#include "securec.h"
#include "sle_device_discovery.h"
#include "sle_errcode.h"

#include "lwip/nettool/misc.h"
#include "lwip/ip4_addr.h"
#include "lwip/netif.h"
#include "lwip/netifapi.h"
#include "lwip/sockets.h"

#include "watchdog.h"
#include "i2c.h"
#include "osal_debug.h"

#include "gpio.h"

#include "adc.h"
#include "adc_porting.h"

#include "securec.h"
#include "sle_uart_server.h"
#include "sle_uart_server_adv.h"
#include "sle_device_discovery.h"
#include "sle_errcode.h"

#include "mydevice/mydevice.h"
#include "module/voc/voc.h"
#include "module/rgb/rgb.h"

#include "function/redoor/redoor.h"

// #include "function/xor/xor.h"
// // [!新增] 定义全局密钥（需与接收端一致）
// static const char xor_key[] = "MySecretKey123";  // 长度建议8-16字节
// static const size_t xor_key_len = sizeof(xor_key)-1;  // 自动计算有效长度


char send_data[100]={0};
SensorData othData = {
    .ligBuffer = "",  // 初始化为空字符串
    .humidity = "",
    .temperature = "",
    .soilHum = "",
    .uv = "",
    .rain = "",
    .id = 999
};
enum state bearpi_oth_flag = UNKNOW;
ControlState othControl;
bool data_requested = false; // 标记是否收到数据请求

// 修改回调函数，增加对getdata指令的解析
static bool parse_getdata_request(ssaps_req_write_cb_t *write_cb_para)
{
    char *data = (char *)write_cb_para->value;
    return (strncmp(data, "getdata", 7) == 0);
}
#define SLE_UART_TASK_PRIO                  28
#define SLE_UART_TASK_DURATION_MS           2000

static uint8_t g_app_uart_int_rx_flag = 0;

static uint8_t g_app_uart_rx_buff[UART_TRANSFER_SIZE] = { 0 };

static uart_buffer_config_t uart_buffer_config = {
    .rx_buffer = g_app_uart_rx_buff,
    .rx_buffer_size = UART_TRANSFER_SIZE
};

#define SLE_UART_SERVER_DELAY_COUNT         5
#define SLE_UART_TASK_STACK_SIZE            0x1200
#define SLE_ADV_HANDLE_DEFAULT              1
#define SLE_UART_SERVER_MSG_QUEUE_LEN       5
#define SLE_UART_SERVER_MSG_QUEUE_MAX_SIZE  32
#define SLE_UART_SERVER_QUEUE_DELAY         0xFFFFFFFF

#define GATHER_TASK_STACK_SIZE 0x1000
#define GATHER_TASK_PRIO (osPriority_t)(17)



unsigned long g_sle_uart_server_msgqueue_id;
#include <string.h> // for strlen, strstr
static void ssaps_server_read_request_cbk(uint8_t server_id, uint16_t conn_id, ssaps_req_read_cb_t *read_cb_para,
    errcode_t status)
{
    osal_printk("%s ssaps read request cbk callback server_id:%x, conn_id:%x, handle:%x, status:%x\r\n",
        SLE_LOG, server_id, conn_id, read_cb_para->handle, status);
}
// SensorData* get_sensor(void){
//     return &othData;
// }

/**
 * 解析控制指令并更新控制状态
 * @param write_cb_para 包含接收到的数据
 * @param othControl 控制状态结构体
 */
static void parse_control_command(ssaps_req_write_cb_t *write_cb_para, ControlState *othControl)
{
    char *data = (char *)write_cb_para->value;
    
    // 解析控制指令: fF:1,wF:1,sF:0,swF:1,r:1,g:1,b:1,
    osal_printk("data:%s\r\n",data);
    if (sscanf(data, "fF:%[^,],wF:%[^,],sF:%[^,],swF:%[^,],r:%[^,],g:%[^,],b:%[^,]",
               othControl->fanFlag, othControl->waterFlag, othControl->sunFlag, othControl->switchFlag, othControl->colorNum[0], othControl->colorNum[1], othControl->colorNum[2]) == 7) {
        // 更新控制状态

        osal_printk("Parse success: fF=%s, wF=%s, sF=%s, swF=%s, r=%s, g=%s, b=%s\r\n",
                    othControl->fanFlag, othControl->waterFlag, othControl->sunFlag, 
                    othControl->switchFlag, othControl->colorNum[0], 
                    othControl->colorNum[1], othControl->colorNum[2]);
        control(othControl);
        
    } else {
        osal_printk("Parse error: invalid control command format\r\n");
    }
}

/**
 * 解析状态上报请求指令
 * @param write_cb_para 包含接收到的数据
 * @return 如果是状态上报请求返回true，否则返回false
 */
static bool parse_status_request(ssaps_req_write_cb_t *write_cb_para)
{
    // 检查是否为状态上报请求: reqStatus:1,
    char *data = (char *)write_cb_para->value;
    return (strncmp(data, "reqStatus:1,", 11) == 0);
}
/**
 * 解析设置ID请求指令
 * @param write_cb_para 包含接收到的数据
 * @param id 解析出的ID值
 * @return 如果是设置ID请求返回true，否则返回false
 */
static bool parse_setid_request(ssaps_req_write_cb_t *write_cb_para)
{
    char *data = (char *)write_cb_para->value;
    if(sscanf(data, "setid:%d,",&othData.id) == 1)
        return true;
    return false;
}

/**
 * 上报当前控制状态
 * @param server_id 服务器ID
 * @param conn_id 连接ID
 * @param othControl 控制状态结构体
 */
static void report_current_status(uint16_t conn_id, const ControlState *othControl)
{
    // 构建上报数据缓冲区
    char report_data[50] = {0};
    
    // 格式化上报数据: 1,fF:1,wF:1,sF:0,swF:1,r:1,g:1,b:1,
    snprintf(report_data, sizeof(report_data), 
             "con,%d,fF:%s,wF:%s,sF:%s,swF:%s,r:%s,g:%s,b:%s,",conn_id,
             othControl->fanFlag, othControl->waterFlag, 
             othControl->sunFlag, othControl->switchFlag,
             othControl->colorNum[0], othControl->colorNum[1], 
             othControl->colorNum[2]);
    
    osal_printk("Reporting status: %s\r\n", report_data);
    
    // 调用发送函数将状态数据发送回主机
    if (sle_uart_client_is_connected()) {
        sle_uart_server_send_report_by_handle((const uint8_t *)report_data, strlen(report_data));
    } else {
        osal_printk("%s 星闪未连接! \r\n", SLE_LOG);
    }
}

/**
 * SSAPS服务器写请求回调函数
 */
static void ssaps_server_write_request_cbk(uint8_t server_id, uint16_t conn_id, ssaps_req_write_cb_t *write_cb_para, errcode_t status)
{
    osal_printk("%s ssaps write request callback cbk server_id:%x, conn_id:%x, handle:%x, status:%x\r\n",
        SLE_LOG, server_id, conn_id, write_cb_para->handle, status);

    if ((write_cb_para->length > 0) && write_cb_para->value) {
        osal_printk("\n sle uart recived data : %s\r\n", write_cb_para->value);

        // // 处理连接ID数据
        // if(write_cb_para->length <= sizeof(uint16_t)){
        //     uint16_t received_conn_id = *((uint16_t *)write_cb_para->value);
        //     osal_printk("Received conn_id from master: %d\r\n", received_conn_id);
        //     othData.id = received_conn_id;
        // }
        if(parse_setid_request(write_cb_para)){

        }
        else if (parse_getdata_request(write_cb_para)) {
            // 收到数据请求，设置标志位
            data_requested = true;
            osal_printk("Received getdata request\r\n");
        }
        // 解析指令类型
        else if (parse_status_request(write_cb_para)) {
            // 处理状态上报请求
            report_current_status(othData.id, &othControl);
        } else {
            // 处理控制指令
            parse_control_command(write_cb_para, &othControl);
        }
    }
}

static void sle_uart_server_create_msgqueue(void)
{
    if (osal_msg_queue_create("sle_uart_server_msgqueue", SLE_UART_SERVER_MSG_QUEUE_LEN, \
        (unsigned long *)&g_sle_uart_server_msgqueue_id, 0, SLE_UART_SERVER_MSG_QUEUE_MAX_SIZE) != OSAL_SUCCESS) {
        osal_printk("^%s sle_uart_server_create_msgqueue message queue create failed!\n", SLE_LOG);
    }
}

static void sle_uart_server_delete_msgqueue(void)
{
    osal_msg_queue_delete(g_sle_uart_server_msgqueue_id);
}

static void sle_uart_server_write_msgqueue(uint8_t *buffer_addr, uint16_t buffer_size)
{
    osal_msg_queue_write_copy(g_sle_uart_server_msgqueue_id, (void *)buffer_addr, \
                              (uint32_t)buffer_size, 0);
}

static int32_t sle_uart_server_receive_msgqueue(uint8_t *buffer_addr, uint32_t *buffer_size)
{
    return osal_msg_queue_read_copy(g_sle_uart_server_msgqueue_id, (void *)buffer_addr, 
                                    buffer_size, SLE_UART_SERVER_QUEUE_DELAY);

}


static void sle_uart_server_rx_buf_init(uint8_t *buffer_addr, uint32_t *buffer_size)
{
    *buffer_size = SLE_UART_SERVER_MSG_QUEUE_MAX_SIZE;
    (void)memset_s(buffer_addr, *buffer_size, 0, *buffer_size);
}
void light_adc_callback(uint8_t ch, uint32_t *buffer, uint32_t length, bool *next)
{
    // UNUSED(next);
    light_data_treating(ch, buffer, length, next, &othData);
    
}
void soilHum_adc_callback(uint8_t ch, uint32_t *buffer, uint32_t length, bool *next){
    soilHum_data_treating(ch, buffer, length, next, &othData);
}
void uv_adc_callback(uint8_t ch, uint32_t *buffer, uint32_t length, bool *next){
    uv_data_treating(ch, buffer, length, next, &othData);
}
void rain_adc_callback(uint8_t ch, uint32_t *buffer, uint32_t length, bool *next){
    rain_data_treating(ch, buffer, length, next, &othData);
}
static void *sle_uart_server_task(const char *arg)
{
    unused(arg);
    uint8_t rx_buf[SLE_UART_SERVER_MSG_QUEUE_MAX_SIZE] = {0};
    uint32_t rx_length = SLE_UART_SERVER_MSG_QUEUE_MAX_SIZE;
    uint8_t sle_connect_state[] = "sle_dis_connect";
    uint8_t sle_connected_state[] = "sle_connected";

    sle_uart_server_create_msgqueue();
    sle_uart_server_register_msg(sle_uart_server_write_msgqueue);
    sle_uart_server_init(ssaps_server_read_request_cbk, ssaps_server_write_request_cbk);
    
    uint8_t ret;
    while (1) {
        sle_uart_server_rx_buf_init(rx_buf, &rx_length);
        sle_uart_server_receive_msgqueue(rx_buf, &rx_length);
        //检查是否收到断开连接
        if (strncmp((const char *)rx_buf, (const char *)sle_connect_state, sizeof(sle_connect_state)) == 0) {
            ret = sle_start_announce(SLE_ADV_HANDLE_DEFAULT);
            if (ret != ERRCODE_SLE_SUCCESS) {
                osal_printk("%s sle_connect_state_changed_cbk,sle_start_announce fail :%02x\r\n",
                    SLE_LOG, ret);
            }
            bearpi_oth_flag=CONNECTING;
        }
        // 检查是否收到连接的指令
        else if (strncmp((const char *)rx_buf, (const char *)sle_connected_state, sizeof(sle_connected_state)) == 0) {
            bearpi_oth_flag=WAIT;// 切换为等待id
            osal_printk("%s sle_connected\r\n", SLE_LOG);
        }
        osal_msleep(SLE_UART_TASK_DURATION_MS);
    }
    sle_uart_server_delete_msgqueue();
    return NULL;
}

static void sle_uart_entry(void)
{
    osal_task *task_handle = NULL;
    osal_kthread_lock();
    task_handle = osal_kthread_create((osal_kthread_handler)sle_uart_server_task, 0, "SLEUartServerTask",
                                      SLE_UART_TASK_STACK_SIZE);
    if (task_handle != NULL) {
        osal_kthread_set_priority(task_handle, SLE_UART_TASK_PRIO);
    }
    osal_kthread_unlock();
}

static void *gather_task(const char *arg)  
{
    UNUSED(arg);
    adc_scan_config_t config = {
                .type = 0,
                .freq = 1,
            };
    char get_id[]="getid";
    // 检查是否有数据需要发送（旋转门算法判断 OR 收到显式请求）
    // bool should_send;
    init_control_state(&othControl);
    //旋转门初始化
    SensorStates states;
    while (1)
    {
        osal_printk("%d\r\n",bearpi_oth_flag);
        switch (bearpi_oth_flag)
        {
        case CONNECTING:{
            osal_printk("connecting\r\n");
            break;
            }
        case WAIT:{
            if (othData.id != 999 && sle_uart_client_is_connected()) {
                bearpi_oth_flag = READY;
                report_current_status(othData.id, &othControl);
                osal_printk("Switch to READY state, ID: %d\r\n", othData.id);
            } else {
                if (sle_uart_client_is_connected()) {
                    sle_uart_server_send_report_by_handle((const uint8_t *)"getid", strlen("getid"));
                } else {
                    osal_printk("%s 星闪未连接! \r\n", SLE_LOG);
                    bearpi_oth_flag = CONNECTING; // 重新连接
                }
            }
            break;
        }
        case READY:{
            RGB_Init();
            init_fan();
            init_water();

           //光照初始化
            uapi_adc_init(ADC_CLOCK_500KHZ);
            uapi_adc_power_en(AFE_SCAN_MODE_MAX_NUM, true);
            
            // 初始化：偏差0.5，时间间隔2秒
            init_sensor_states(&states, 0.5f, 2.0f);

            bearpi_oth_flag=RUNNING;
            osal_printk("to runing\r\n");
            break;
            }
        case RUNNING:{
            osal_printk(" runing\r\n");
            
            // 判断是否需要发送数据
            // 检查是否有数据需要发送（旋转门算法判断 OR 收到显式请求）
            // should_send = should_send_data(&othData, &states) || data_requested;
            if (othControl.switchFlag[0]=='1') {
                // 发送数据...
                print_sensor_data(&othData);//打印一下
                //--------------------------------------
                snprintf(send_data, sizeof(send_data), "begin,%d,Hum:56.1,Tem:34.5,Lig:30,SoilHum:28,uv:0,rain:0,co2:860,over", 
                othData.id);
                if (sle_uart_client_is_connected()) {
                    sle_uart_server_send_report_by_handle((const uint8_t *)send_data, strlen(send_data));
                } else {
                    osal_printk("%s 星闪未连接! \r\n", SLE_LOG);
                    othData.id =999;
                }
                // 重置请求标志
                data_requested = false;
            }
            else{
                osal_printk("%s压缩中! \r\n", XZM_LOG);
            }
            

             //--------------------------------------发送状态
            // snprintf(send_data, sizeof(send_data), "2,LED:%d,Water:%d,Fan:%d,R:%d,G:%d,B:%d,over",
            //     atoi(othControl.switchFlag),     // LED 开关状态
            //     atoi(othControl.waterFlag),      // 水泵状态
            //     atoi(othControl.fanFlag),        // 风扇状态
            //     atoi(othControl.colorNum[0]),    // R 值
            //     atoi(othControl.colorNum[1]),    // G 值
            //     atoi(othControl.colorNum[2]));   // B 值
            // if (sle_uart_client_is_connected()) {
            //     sle_uart_server_send_report_by_handle((const uint8_t *)send_data, strlen(send_data));
            // } else {
            //     osal_printk("%s 星闪未连接! \r\n", SLE_LOG);
            // }
            }
            break;
            
        case STOP:
            osal_printk("stop\r\n");
            break;

        default:
            osal_printk("default\r\n");
            break;
        
            
            // print_sensor_data
        }
        // snprintf(send_data, sizeof(send_data), "2,Hum:%s,Tem:%s,Lig:%s,SoilHum:%s,over", othData.humidity, othData.temperature,othData.ligBuffer,othData.soilHum);
        //             if (sle_uart_client_is_connected()) {
        //                 sle_uart_server_send_report_by_handle((const uint8_t *)send_data, strlen(send_data));
        //             } else {
        //                 osal_printk("%s 星闪未连接! \r\n", SLE_LOG);
        //             }
        osal_printk("A running\r\n");
        osal_msleep(3000);
    }

    return NULL;
            }

static void gather_entry(void)
{
    osThreadAttr_t attr;

    attr.name = "gatherTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = GATHER_TASK_STACK_SIZE;
    attr.priority = GATHER_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)gather_task, NULL, &attr) == NULL)
    {
        osal_printk("Failed to create gather task.\r\n");
        osal_printk("创建采集任务失败！\r\n");
    }
}

app_run(gather_entry);
app_run(sle_uart_entry);